#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import logging
import traceback
from store.store import BasicStore


# 存redis, rds为redis连接
class RdsStore(BasicStore):
    def __init__(self, config):
        self.rds = config['rds']

    def set(self, key, data, extra=None):
        # 复合类型，json dump处理
        if isinstance(data, dict) or isinstance(data, list):
            value = json.dumps(data)
        else:
            value = data
        if extra is None:
            return self.rds.set(key, value)
        if 'ex' in extra and 'nx' in extra:
            return self.rds.set(key, value, ex=extra['ex'], nx=extra['nx'])
        elif 'ex' in extra:
            return self.rds.set(key, value, ex=extra['ex'])
        elif 'nx' in extra:
            return self.rds.set(key, value, nx=extra['nx'])
        else:
            return self.rds.set(key, value)

    def get(self, key, extra=None):
        value = self.rds.get(key)
        if value is None:
            return value
        try:
            data = json.loads(value)
        except json.decoder.JSONDecodeError:
            return value
        except Exception as e:
            logging.error('rds get key {} extra {} except {}'.format(key, extra, e))
            logging.error(traceback.format_exc())
            return value
        return data
